package cn.arithmetic;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @创建人: WangShuai
 * @描述:汉明距离：将一个字符串变换成另外一个字符串所需要替换的字符个数 给定两个整数，x并y计算汉明距离。
 * @创建时间: 2018/2/8 10:32
 */
public class HammingDistance461 {

    @Test
    public int  hammingDistance1(int x,int y) {

        int k = 0;
        List a = Arrays.asList(Integer.toBinaryString(x).split(""));
        List b = Arrays.asList(Integer.toBinaryString(y).split(""));
        List c = new ArrayList();
        List d = new ArrayList();
        if (a.size() > b.size()) {
            for (int i = 0; i < a.size() - b.size(); i++) {
                c.add(i, "0");
            }

            d.addAll(c);
            d.addAll(b);


        } else {
            for (int i = 0; i < b.size() - a.size(); i++) {
                c.add(i, "0");
            }

            d.addAll(c);
            d.addAll(a);

        }

        if (a.size() > b.size()) {
            for (int i = 0; i < d.size(); i++) {
                if (!(d.get(i).equals(a.get(i)))) {
                    k++;
                }
            }
           return  k;
        } else {
            for (int i = 0; i < d.size(); i++) {
                if (!(d.get(i).equals(b.get(i)))) {
                    k++;
                }
            }
           return k;
        }


    }


    //标准答案
    @Test
    public void   call () {

        System.out.println(hammingDistance1(5,13));
        System.out.println(hammingDistance(5,13));

    }
    public int hammingDistance(int x, int y) {
        int num = x ^ y;
        String numStr = Integer.toBinaryString(num);

        int result = 0;
        for (int i = 0; i < numStr.length(); i++) {
            if (numStr.charAt(i) == '1') {
                result++;
            }
        }

        return result;
    }
    public void   copy (int x,int y) {

        String k = Integer.toBinaryString(x^y);
        int num=0;
        for (int i = 0; i <k.length() ; i++) {
            if (k.charAt(i)==1){
                num++;
            }
        }


    }
}